本文共 2472 字,大约阅读时间需要 8 分钟。
This guide introduces a practical approach to parsing and analyzing text using C++. The goal of this project is to create a straightforward program that extracts unique words from a given input, sorts them alphabetically, and displays them in a readable format.
The solution involves reading an input string, processing it to identify words, and storing these words in a set for automatic sorting. The program also includes error handling and case insensitivity to ensure robust performance across different inputs.
The program reads input one word at a time using standard input. Each word is treated as a continuous sequence of characters. The code converts all alphabetic characters to lowercase to ensure uniformity, while non-alphabetic characters are replaced with spaces. This step ensures that words are consistently formatted regardless of their original case.
Using a stringstream, the program iterates over the input string to extract words. Each word is inserted into a set, which automatically handles storage and sorting based on lexicographical order.
Finally, the program prints out each word from the set, ensuring the results are displayed in alphabetical order.
#include#include #include #include using namespace std;int main() { string dict; string s; while (cin >> s) { for (int i = 0; i < s.size(); ++i) { if (isalpha(s[i])) { s[i] = tolower(s[i]); } else { s[i] = ' '; } } stringstream ss(s); string buf; while (ss >> buf) { dict.insert(buf); } } for (set ::iterator it = dict.begin(); it != dict.end(); ++it) { cout << *it << endl; } return 0;}
This project provides a solid foundation for processing textual data using C++ and sets up a good basis for more advanced applications in natural language processing.
转载地址:http://uoipz.baihongyu.com/